package com.khalil.kkadmin.system.dms.store.db;

import com.khalil.kkadmin.common.util.JsonUtil;
import com.khalil.kkadmin.system.dms.store.DocumentStore;
import com.khalil.kkadmin.system.dms.store.DocumentStoreInfo;
import com.khalil.kkadmin.system.dms.store.StoreType;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Base64;
import java.util.List;

@Service
public class DatabaseDocumentStore implements DocumentStore {

    private final DocumentFileRepository repository;

    public DatabaseDocumentStore(DocumentFileRepository repository) {
        this.repository = repository;
    }


    @Override
    public boolean support(StoreType type) {
        return StoreType.DB.equals(type);
    }

    @Override
    public DocumentStoreInfo store(DocumentStoreInfo documentStoreInfo) {
        String filename = documentStoreInfo.getFilename();
        List<String> pathArr = documentStoreInfo.getPathArr();
        String path = JsonUtil.toJsonStr(pathArr);
        InputStream inputStream = documentStoreInfo.getInputStream();
        try {
            byte[] byteArray = IOUtils.toByteArray(inputStream);
            String bytes = Base64.getEncoder().encodeToString(byteArray);
            DocumentFile documentFile = new DocumentFile();
            documentFile.setPath(path);
            documentFile.setFilename(filename);
            documentFile.setBytes(bytes);
            repository.save(documentFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return documentStoreInfo;
    }

    @Override
    public DocumentStoreInfo getDocumentStoreInfo(List<String> pathArr, String filename) {
        String path = JsonUtil.toJsonStr(pathArr);
        DocumentFile documentFile = repository.findByPathAndFilename(path, filename);
        if (documentFile == null) {
            throw new RuntimeException("文件不存在");
        }
        String bytes = documentFile.getBytes();

        byte[] decoded = Base64.getDecoder().decode(bytes);
        InputStream inputStream = new ByteArrayInputStream(decoded);
        return DocumentStoreInfo.builder()
                .filename(filename)
                .pathArr(pathArr)
                .inputStream(inputStream)
                .build();
    }

    @Override
    public void delete(List<String> pathArr, String filename) {
        repository.deleteByPathAndFilename((JsonUtil.toJsonStr(pathArr)), filename);
    }
}
